﻿using System;
using System.Collections.Generic;
using Yto.Common.Dependency;

namespace Yto.Threading.BackgroundWorkers
{
    public class BackgroundManager : BaseRunnable, IBackgroundManager, ISingleton, IDisposable
    {
        private readonly ICtnResolver _ctnResolver;
        private readonly List<IBackgroundWorker> _listWorkers;

        public BackgroundManager(ICtnResolver ctnResolver)
        {
            _ctnResolver = ctnResolver;
            _listWorkers = new List<IBackgroundWorker>();
        }

        public void Add(IBackgroundWorker worker)
        {
            _listWorkers.Add(worker);
            if (IsRunning)
            {
                worker.Start();
            }

        }

        private bool _isDisposed;
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }
            _isDisposed = true;
            Wait2Stop();
            _listWorkers.ForEach(_ctnResolver.Realse);
            _listWorkers.Clear();
        }

        public override void Start()
        {
            base.Start();

            _listWorkers.ForEach(x => x.Start());
        }

        public override void Stop()
        {
            _listWorkers.ForEach(x => x.Stop());

            base.Stop();
        }

        public override void Wait2Stop()
        {
            _listWorkers.ForEach(x => x.Wait2Stop());

            base.Wait2Stop();
        }
    }
}
